import { ref, computed } from 'vue'

/**
 * 倒计时
 * @param second 倒计时秒数
 */
export default function useCountDown(second: number) {
  if (second <= 0 && second % 1 != 0) {
    throw Error('倒计时时间应该为一个正整数')
  }
  // 每次调用 useCountDown 都会形成一个独立的闭包
  const counts = ref(0)
  const isCounting = computed(() => Boolean(counts.value))
  let intervalId: number | undefined
  /**
   * 开始倒计时
   * @param updatedSecon 更改默认的倒计时时间
   */
  function start(updateSecond: number = second) {
    if (!counts.value) {
      counts.value = updateSecond
      intervalId = window.setInterval(() => {
        counts.value -= 1
        if (counts.value <= 0) {
          clearInterval(intervalId)
        }
      }, 1000)
    }
  }

  function stop() {
    clearInterval(intervalId)
    intervalId = undefined
    counts.value = 0
  }

  return {
    counts,
    isCounting,
    start,
    stop,
  }
}
